package com.ztesoft.report.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztesoft.report.IsPermission.annotion.isPermission;
import com.ztesoft.report.base.controller.BaseController;
import com.ztesoft.report.base.pojo.R;
import com.ztesoft.report.dao.DatasourceDao;
import com.ztesoft.report.engine.dbpool.DruidDataSourcePool;
import com.ztesoft.report.engine.query.MySqlQueryer;
import com.ztesoft.report.engine.query.OracleQueryer;
import com.ztesoft.report.entity.Datasource;
import com.ztesoft.report.entity.Report;
import com.ztesoft.report.entity.ReportData;
import com.ztesoft.report.service.DatasourceService;
import com.ztesoft.report.service.ReportDataService;
import com.ztesoft.report.service.ReportService;
import com.ztesoft.report.utils.AESUtil;
import com.ztesoft.report.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据源配置信息表 前端控制器
 * </p>
 *
 * @author xie
 * @since 2018-06-11
 */
@RestController
@RequestMapping("/datasource")
@CrossOrigin
public class DatasourceController extends BaseController {

    @Autowired
    private DatasourceService datasourceService;
    @Autowired
    private DatasourceDao datasourceDao;
    @Autowired
    private ReportDataService reportDataService;
    @Autowired
    private ReportService reportService;

    public Object test(@RequestBody Long id) {
        //测试方法，代码生成后，请删除
        return R.ok("操作成功", id);
    }

    /**
     * 验证用户是否具有数据源管理编辑按钮权限
     * @return
     */
    @isPermission(name = "sys:dataSrouce:edit")
    @RequestMapping("/VerificateDataSourceEdit")
    public Object VerificateDataSourceEdit() {
        //测试方法，代码生成后，请删除
        return R.ok("操作成功");
    }

    /**
     * 查询数据源表中所有配置的数据源信息
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> datasourceList(@RequestParam(required = false)String type,
                                           @RequestParam(required = false)String name,String pageSize,
                                           String pageNumber){

        Map<String,Object> result = new HashMap<String,Object>();
        Page<Datasource> page = new Page<>(Integer.parseInt(pageNumber), Integer.parseInt(pageSize));
        EntityWrapper<Datasource> wrapper = new EntityWrapper<>();
        if (type!=null&&type!=""){
            wrapper.eq("DATASOURCE_TYPE",type);
        }
        if (name!=null&&name!=""){
            wrapper.like("NAME",name);
        }
        Page<Datasource> userPage = datasourceService.selectPage(page, wrapper);

        List<Datasource> datasourceList=datasourceDao.selectDataByNameOrJdbc(name,type);

        userPage.getRecords().forEach(e->{
            e.setPassword(AESUtil.decrypt(e.getPassword()));
            System.out.println(e.getPassword());
        });
        result.put("total", datasourceList.size());
        result.put("rows", userPage.getRecords());
        return  result;
    }
    @RequestMapping("/listdataSource")
    @ResponseBody
    public List<Datasource> datasourceList(){
        return datasourceService.selectList(null);
    }

    /**
     * 新增一条数据
     * @param datasource
     * @return
     */
    @PostMapping("/add")
    public  R add(@RequestBody Datasource datasource){

        datasource.setCreateTime(DateUtil.toDate(DateUtil.getDateTime(),"yyyyMMdd HH:mm:ss"));
        datasource.setUpdateTime(DateUtil.toDate(DateUtil.getDateTime(),"yyyyMMdd HH:mm:ss"));
        datasource.setCreateUser(getCurrentUser());
        datasource.setUpdateUser(getCurrentUser());
        datasource.setPoolClass(DruidDataSourcePool.class.getName());
        datasource.setOptions("{\"initialSize\":3,\"maxActive\":20,\"minIdle\":1,\"maxWait\":60000,\"timeBetweenEvictionRunsMillis\":60000,\"minEvictableIdleTimeMillis\":300000,\"testWhileIdle\":true,\"testOnBorrow\":false,\"testOnReturn\":false,\"maxOpenPreparedStatements\":20,\"removeAbandoned\":true,\"removeAbandonedTimeout\":1800,\"logAbandoned\":true}");
        if (datasource.getDatasourceType()=="2"){
            datasource.setQueryerClass(OracleQueryer.class.getName());
        }
        else {
            datasource.setQueryerClass(MySqlQueryer.class.getName());
        }
        datasource.setPassword(AESUtil.encrypt(datasource.getPassword()));
        boolean i=datasourceService.insert(datasource);
        if (i==true)
            return R.ok("操作成功", datasource.getId());
        else
            return R.error("操作失败") ;
    }

    /**
     * 编辑一条数据
     * @param datasource
     * @return
     */
    @PostMapping("/edit")
    public  R edit(@RequestBody Datasource datasource){

        datasource.setPassword(AESUtil.encrypt(datasource.getPassword()));
        if (datasource.getDatasourceType()=="1"){
            datasource.setQueryerClass(OracleQueryer.class.getName());
        }
        else {
            datasource.setQueryerClass(MySqlQueryer.class.getName());
        }
        boolean i=datasourceService.updateById(datasource);
        if (i==true)
            return R.ok("操作成功", datasource.getId());
        else
            return R.error("操作失败") ;
    }

    /**
     * 删除一条数据
     * @param datasource
     * @return
     */
    @PostMapping("/delete")
    public  R delete(@RequestBody Datasource datasource){

        //验证当前数据源是否在report_data表存在且状态正常
        EntityWrapper<ReportData> wrapper = new EntityWrapper<>();
        wrapper.eq("status","00A");
        wrapper.eq("ds_id",datasource.getId());
        List<ReportData> reportDataList=reportDataService.selectList(wrapper);

        if (reportDataList!=null&&reportDataList.size()!=0){
            return R.error("报表数据生成配置中有引用当前数据源，不允许删除") ;
        }
        EntityWrapper<Report> wrapperReport = new EntityWrapper<>();
        wrapperReport.eq("status","00A");
        wrapperReport.eq("ds_id",datasource.getId());
        List<Report> reportList=reportService.selectList(wrapperReport);

        if (reportList!=null&&reportList.size()!=0){
            return R.error("报表信息中有引用当前数据源，不允许删除") ;
        }

        boolean i=datasourceService.deleteById(datasource);
        if (i==true)
            return R.ok("操作成功", datasource.getId());
        else
            return R.error("操作失败") ;
    }

    /**
     * 测试链接
     * @param datasource
     * @return
     */
    @PostMapping("/testConnect")
    public R testConnect(@RequestBody Datasource datasource){
        R r=testConnect(datasource.getJdbcUrl(),datasource.getDatasourceUser(),datasource.getPassword(),datasource.getDriverClass());
        return r;
    }



    public R testConnect(String url,String user,String password,String jdbc){

        try {
            Class.forName(jdbc);
            //2.获得数据库链接
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement st=conn.createStatement();
          return    R.ok("连接成功");
        }catch (Exception e){
            return  R.error("连接失败:请检查配置");
        }
    }


}
